package common.web;

import common.CommonConstants;
import common.model.WebUser;
import common.util.DbUtil;
import common.util.FacesUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

/**
 *
 * @author shousuke
 */
public class LoginController extends GenericSessionController {

    private WebUser user = null;

    public WebUser getUser() {
        if (user == null) {
            user = new WebUser();
        }
        return user;
    }

    /**
     * Performs user login
     * 
     * Pre-condition: username and password are available
     * Post-condition: webUser is set in session and in controller
     * 
     * @return Navigation outcome
     */
    public String login() {
        String username = user.getUsername();
        String password = user.getPassword();
        Map<String, Object> queryParam = new HashMap<String, Object>();
        queryParam.put("username", username);
        WebUser u = (WebUser) DbUtil.getSingleResult(getEntityManager(), "WebUser.findByUsername", queryParam);
        if (u != null && u.getPassword().equals(password)) {
            user = u;
            FacesUtil.setSessionMapValue(CommonConstants.SSN_CUR_WEB_USER, u);
            return "home";
        } else {
            FacesUtil.addErrorMessage("The username or password specified is incorrect.");
            return null;
        }
    }

    /**
     * Invalidates the current session and navigates the user to the login page
     * 
     * @return Navigation outcome: login
     */
    public String logout() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return "logout";
    }

    public void validateEmail(FacesContext context, UIComponent componentToValidate, Object value) throws ValidatorException {
        String email = value.toString().trim();
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(email);
        if (!m.matches()) {
            FacesMessage message = new FacesMessage("Invalid email address. Please check.");
            throw new ValidatorException(message);
        }
    }
}
